#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Word文档转静态网页脚本
运行方式: python convert.py
"""

import os
from pathlib import Path
from docx import Document
import re
import html

def extract_text_from_docx(docx_path):
    """从Word文档中提取纯文本内容"""
    if not os.path.exists(docx_path):
        print(f"错误：找不到文件 {docx_path}")
        return None
    
    try:
        doc = Document(docx_path)
        full_text = []
        
        # 提取段落文本
        for paragraph in doc.paragraphs:
            text = paragraph.text.strip()
            if text:  # 跳过空段落
                full_text.append(text)
        
        # 提取表格中的文本
        for table in doc.tables:
            for row in table.rows:
                row_text = []
                for cell in row.cells:
                    cell_text = cell.text.strip()
                    if cell_text:
                        row_text.append(cell_text)
                if row_text:
                    full_text.append(" | ".join(row_text))
        
        return "\n\n".join(full_text)
    
    except Exception as e:
        print(f"读取Word文档时出错: {e}")
        return None

def text_to_html(text, title="文档内容"):
    """将纯文本转换为格式化的HTML"""
    if not text:
        return None
    
    # 转义HTML特殊字符
    text = html.escape(text)
    
    # 将换行符转换为段落
    paragraphs = text.split('\n\n')
    
    # 构建HTML内容
    html_content = []
    for para in paragraphs:
        if para.strip():
            # 检查是否为标题（全大写或以数字开头）
            if para.isupper() or re.match(r'^\d+\.', para.strip()):
                html_content.append(f'<h2>{para.strip()}</h2>')
            else:
                html_content.append(f'<p>{para.strip()}</p>')
    
    return '\n'.join(html_content)

def generate_html(content, title="文档内容", output_path="index.html"):
    """生成完整的HTML文件"""
    html_template = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}
        
        body {{
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8f9fa;
            padding: 20px;
        }}
        
        .container {{
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        
        h1 {{
            color: #2c3e50;
            margin-bottom: 30px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3498db;
        }}
        
        h2 {{
            color: #34495e;
            margin: 25px 0 15px 0;
            font-size: 1.5em;
        }}
        
        p {{
            margin-bottom: 15px;
            text-align: justify;
            font-size: 16px;
            line-height: 1.8;
        }}
        
        @media (max-width: 600px) {{
            body {{
                padding: 10px;
            }}
            
            .container {{
                padding: 20px;
            }}
            
            h1 {{
                font-size: 1.5em;
            }}
            
            h2 {{
                font-size: 1.3em;
            }}
            
            p {{
                font-size: 15px;
            }}
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>{title}</h1>
        {content}
    </div>
</body>
</html>"""
    
    try:
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(html_template)
        print(f"✅ HTML文件已生成: {output_path}")
        return True
    except Exception as e:
        print(f"生成HTML文件时出错: {e}")
        return False

def main():
    """主函数"""
    print("🚀 Word文档转静态网页工具")
    print("=" * 40)
    
    # 查找Word文档
    docx_files = [f for f in os.listdir('.') if f.endswith('.docx')]
    
    if not docx_files:
        print("❌ 当前目录下没有找到.docx文件")
        print("请将Word文档放在当前目录后重试")
        return
    
    # 使用第一个找到的Word文档
    input_file = docx_files[0]
    print(f"📄 找到Word文档: {input_file}")
    
    # 提取文本
    print("🔄 正在提取文档内容...")
    text_content = extract_text_from_docx(input_file)
    
    if not text_content:
        print("❌ 无法提取文档内容")
        return
    
    # 生成标题（使用文件名，去掉扩展名）
    title = os.path.splitext(input_file)[0]
    
    # 转换为HTML
    print("🔄 正在转换为HTML格式...")
    html_content = text_to_html(text_content, title)
    
    if not html_content:
        print("❌ 无法转换内容为HTML")
        return
    
    # 生成HTML文件
    if generate_html(html_content, title):
        print("✅ 转换完成！")
        print(f"📁 生成的文件: index.html")
        print("💡 现在可以直接双击 index.html 在浏览器中查看")
    else:
        print("❌ 转换失败")

if __name__ == "__main__":
    # 检查依赖
    try:
        from docx import Document
    except ImportError:
        print("❌ 缺少依赖库 python-docx")
        print("请运行: pip install python-docx")
        exit(1)
    
    main()
